package seckill;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import java.util.List;


/**
 * @author 帅小伙
 * @date 2021/12/31
 * @description
 */
public class SecKillRedis {

    /**
     *
     */
    boolean doSecKill(String uid, String propid) {
        //判空
        if (uid == null || propid == null) {
            return false;
        }

        //连接redis
        //Jedis jedis = new Jedis("47.96.19.90", 23333);
        Jedis jedis = JedisPoolUtil.getJedisPoolInstance().getResource();
        //拼接key
        //3.1库存key
        String storeKey = "sk:" + propid + ":qt";
        //3.2秒杀成功用户key
        String userKey = "sk:" + propid + ":us";
        //4 获取库存并判断   如果库存为null  秒杀还没开始
        jedis.watch(storeKey);
        String s = jedis.get(storeKey);
        if (s == null) {
            System.out.println("秒杀还没有开始");
            jedis.close();
            return false;
        }
        //5 判断用户是否重复秒杀操作
        if (jedis.sismember(userKey, uid)) {
            System.out.println("已经成功秒杀 请重复操作");
            jedis.close();
            return false;
        }

        jedis.watch(storeKey);
        //6 判断商品数量 是否合理
        if (Integer.parseInt(s) <= 0) {
            System.out.println("商品已经秒杀完了");
            jedis.close();
            return false;
        }

        //7 秒杀过程
        //7.1库存-1
        //7.2秒杀用户
        Transaction multi = jedis.multi();
        multi.decr(storeKey);
        multi.sadd(userKey, uid);
        List<Object> exec = multi.exec();
        if (exec==null||exec.size() == 0) {
            return false;
        }
        //jedis.decr(storeKey);
        //jedis.sadd(userKey, uid);
        jedis.close();
        System.out.println("秒杀成功");
        return true;
    }
}
